package rmiClient;

import interfaces.Client_ITF;
import interfaces.Serveur_ITF;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import rmiServeur.ServerBusy;

public class Lanceur_Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length != 1) {
			System.err
					.println("Usage : java client <server name or address:port number>");
			System.exit(1);
		}

		Serveur_ITF server = null;

		try {
			server = (Serveur_ITF) Naming
					.lookup("rmi://" + args[0] + "/server");
		} catch (MalformedURLException e) {
			System.err
					.println("The server name/address:port is malformed\nsomething like turing.u-strasbg.fr:1099 or 130.79.7.1:1099 is expected");
			System.exit(2);
		} catch (RemoteException e) {
			System.err
					.println("The server cannot be reach or an error occurs on the server");
			System.exit(3);
		} catch (NotBoundException e) {
			System.err
					.println("No server object has been binded on the server");
			System.exit(4);
		}

		Client_IMPL c = null;
		try {
			c = new Client_IMPL(server, 1, 1, "localhost", "/");
		} catch (RemoteException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		try {
			server.addClient(c);
		} catch (RemoteException e) {
			System.err
					.println("Due to an error on the server the client cannot be registred");
			System.exit(5);
		} catch (ServerBusy e) {
			System.err.println("ServerBusy");
			System.exit(5);
		}

		try {
			for (Client_ITF newNeighbor : server.getNeighbors(c)) {
				c.neighbors.put(newNeighbor.getId(), newNeighbor);
			}
		} catch (RemoteException e) {
			System.err
					.println("Due to an error on the server the neighbors list cannot be retrive from the server");
			System.exit(6);
		}

		System.out.println("Le client est correcetment connecté");
		// Fore testing purpose
		while (true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
